<template>
  <page-container :title="isEdit ? '编辑任务' : '新增任务'">
    <el-form
      ref="jobForm"
      :model="jobForm"
      :rules="rules"
      label-width="120px"
      class="job-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="jobForm.jobName" placeholder="请输入任务名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务组名" prop="jobGroup">
            <el-input v-model="jobForm.jobGroup" placeholder="请输入任务组名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="执行类路径" prop="jobClassPath">
            <el-input v-model="jobForm.jobClassPath" placeholder="请输入任务执行类的全路径"></el-input>
            <div class="form-hint">提示：类需继承BaseJob，并重写execute方法</div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="Cron表达式" prop="cronExpression">
            <el-input 
              v-model="jobForm.cronExpression" 
              placeholder="请输入Cron表达式"
              @blur="validateCron"
            ></el-input>
            <div class="form-hint" v-if="cronHint">
              {{ cronHint }}
            </div>
            <div class="form-error" v-if="cronError">
              {{ cronError }}
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="Cron表达式生成" prop="">
            <cron-editor v-model="jobForm.cronExpression"></cron-editor>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="任务参数" prop="parameter">
            <el-input 
              v-model="jobForm.parameter" 
              placeholder="请输入任务参数，JSON格式"
              type="textarea"
              rows="3"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="jobForm.status">
              <el-radio :label="1">运行中</el-radio>
              <el-radio :label="0">已暂停</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="允许并发执行" prop="concurrent">
            <el-radio-group v-model="jobForm.concurrent">
              <el-radio :label="1">允许</el-radio>
              <el-radio :label="0">禁止</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="jobForm.remark" 
              placeholder="请输入备注信息"
              type="textarea"
              rows="2"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item class="form-actions">
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<script>
import { mapActions } from 'vuex'
import { getJobDetail } from '@/api/job'
import PageContainer from '@/components/common/PageContainer.vue'
import CronEditor from '@/components/job/CronEditor.vue'
import { validateCronExpression, getCronDescription } from '@/utils/cron'

export default {
  name: 'JobForm',
  components: {
    PageContainer,
    CronEditor
  },
  data() {
    return {
      isEdit: false,
      jobId: null,
      jobForm: {
        jobName: '',
        jobGroup: 'DEFAULT_GROUP',
        jobClassPath: '',
        cronExpression: '',
        parameter: '',
        status: 0,
        concurrent: 0,
        remark: ''
      },
      rules: {
        jobName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { max: 100, message: '任务名称不能超过100个字符', trigger: 'blur' }
        ],
        jobGroup: [
          { required: true, message: '请输入任务组名', trigger: 'blur' },
          { max: 100, message: '任务组名不能超过100个字符', trigger: 'blur' }
        ],
        jobClassPath: [
          { required: true, message: '请输入执行类路径', trigger: 'blur' },
          { max: 255, message: '执行类路径不能超过255个字符', trigger: 'blur' }
        ],
        cronExpression: [
          { required: true, message: '请输入Cron表达式', trigger: 'blur' },
          { validator: this.validateCronRule, trigger: 'blur' }
        ]
      },
      cronHint: '',
      cronError: ''
    }
  },
  methods: {
    ...mapActions({
      addJob: 'job/addJob',
      updateJob: 'job/updateJob'
    }),
    
    // 验证Cron表达式规则
    validateCronRule(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入Cron表达式'))
        return
      }
      
      if (validateCronExpression(value)) {
        this.cronError = ''
        this.cronHint = getCronDescription(value)
        callback()
      } else {
        this.cronError = 'Cron表达式格式不正确'
        this.cronHint = ''
        callback(new Error('Cron表达式格式不正确'))
      }
    },
    
    // 验证Cron表达式
    validateCron() {
      if (!this.jobForm.cronExpression) return
      
      if (validateCronExpression(this.jobForm.cronExpression)) {
        this.cronError = ''
        this.cronHint = getCronDescription(this.jobForm.cronExpression)
      } else {
        this.cronError = 'Cron表达式格式不正确'
        this.cronHint = ''
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.jobForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateJob({
              id: this.jobId,
              jobForm: this.jobForm
            }).then(() => {
              this.$message.success('任务更新成功')
              this.$router.push('/job/list')
            })
          } else {
            this.addJob(this.jobForm).then(() => {
              this.$message.success('任务新增成功')
              this.$router.push('/job/list')
            })
          }
        }
      })
    },
    
    // 取消
    handleCancel() {
      this.$router.go(-1)
    },
    
    // 获取任务详情
    getJobDetail() {
      getJobDetail(this.jobId).then(response => {
        this.jobForm = response.data
      })
    }
  },
  created() {
    const id = this.$route.params.id
    if (id) {
      this.isEdit = true
      this.jobId = id
      this.getJobDetail()
    }
  }
}
</script>

<style scoped>
.job-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-hint {
  color: #67c23a;
  font-size: 12px;
  margin-top: 5px;
}

.form-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style>
